#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "HashMap.h"

// 哈希函数
unsigned int hash(const char* key, int capacity) {
    unsigned int hash = 0;
    for (int i = 0; key[i] != '\0'; i++) {
        hash = (hash * 31) + key[i];
    }
    return hash % capacity;
}

// 创建一个新的HashMap
HashMap* createHashMap() {
    HashMap* map = (HashMap*)malloc(sizeof(HashMap));
    if (map) {
        map->capacity = INITIAL_CAPACITY;
        map->size = 0;
        map->table = (KeyValuePair**)calloc(map->capacity, sizeof(KeyValuePair*));
    }
    return map;
}

// 插入键-值对
void put(HashMap* map, const char* key, int value) {
    if (!map || !key) {
        return;
    }

    unsigned int index = hash(key, map->capacity);
    KeyValuePair* newNode = (KeyValuePair*)malloc(sizeof(KeyValuePair));
    if (!newNode) {
        return;
    }

    newNode->key = strdup(key);
    newNode->value = value;
    newNode->next = map->table[index];
    map->table[index] = newNode;
    map->size++;
}

// 根据键获取值
int get(HashMap* map, const char* key) {
    if (!map || !key) {
        return 0;
    }

    unsigned int index = hash(key, map->capacity);
    KeyValuePair* current = map->table[index];
    while (current != NULL) {
        if (strcmp(current->key, key) == 0) {
            return current->value;
        }
        current = current->next;
    }

    return 0; // 未找到键，返回默认值
}

// 销毁HashMap
void destroyHashMap(HashMap* map) {
    if (!map) {
        return;
    }

    for (int i = 0; i < map->capacity; i++) {
        KeyValuePair* current = map->table[i];
        while (current != NULL) {
            KeyValuePair* next = current->next;
            free(current->key);
            free(current);
            current = next;
        }
    }

    free(map->table);
    free(map);
}

int main_test() {
    HashMap* map = createHashMap();

    put(map, "apple", 42);
    put(map, "banana", 23);
    put(map, "cherry", 17);

    int value = get(map, "banana");
    printf("Value for key 'banana': %d\n", value);

    destroyHashMap(map);

    return 0;
}

